package com.lagou.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置请求和响应的编码
 */
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将servlet的request和response强转为Httpservlet的request和response，以便于进行session的操作
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        //如果是post 才设置请求编码
        if("post".equalsIgnoreCase(req.getMethod())){
            req.setCharacterEncoding("UTF-8");
        }
        //响应码设置为utf-8
        resp.setContentType("text/html;charset=UTF-8");
        //放行
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
